<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app">
      <a-tabs v-model:activeKey="data.activeKey">
        <a-tab-pane key="1" tab="概要">







          <a-row justify="space-between">
            <a-col :span="12">
              <a-space :size="20">
                <h2 style="display: inline">
                  <CaretLeftFilled @click="back()" />
                </h2>
                <h2 style="display: inline">生产领料单</h2>
                <h3 style="display: inline">{{ data.form.id }} </h3>
                <a-space :size="12">
                  <a-button shape="circle">
                    {{ data.form.docStatus }}
                  </a-button>
                  <a-button shape="circle">
                    <LockOutlined />
                  </a-button>
                  <a-button shape="circle" :type="data.form.approved ? 'primary' : 'default'">
                    <CheckOutlined />
                  </a-button>
                  <a-button shape="circle">
                    <FlagOutlined />
                  </a-button>

                  <a-button shape="circle" @click="print()">

                    <PrinterOutlined />
                  </a-button>


                </a-space>
              </a-space>
            </a-col>
            <a-col :span="12">
              <a-row justify="end">
                <a-space :size="6" v-if="!data.form.edit">
                  <a-button size="small" type="primary" @click="edit()"
                    v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved)">
                    <FormOutlined />
                    编辑
                  </a-button>
                  <a-button size="small" type="primary" danger @click="del()"
                    v-if="data.form.docStatus === 'O' && !data.form.approved">
                    <DeleteOutlined />删除
                  </a-button>
                  <a-dropdown>
                    <a-button size="small"   v-if="!(data.form.docStatus === 'L')">更多操作
                      <DownOutlined />
                    </a-button>
                    <template #overlay>
                      <a-menu @click="more">
                        <a-menu-item key="a" v-if="data.form.docStatus !== 'C'">关闭单据</a-menu-item>
                        <a-menu-item key="b" v-if="data.form.docStatus === 'C'">打开单据</a-menu-item>

                        <a-menu-item key="c" v-if="!data.form.approved">发起审核</a-menu-item>
                        <a-menu-item key="d" v-if="data.form.approved">取消审核</a-menu-item>


                      </a-menu>
                    </template>
                  </a-dropdown>
                  <a-button size="small" @click="refresh">
                    <RetweetOutlined />
                    刷新
                  </a-button>
                </a-space>
              </a-row>
            </a-col>
          </a-row>









          <br />





          <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 4 }">
            <a-row class="smart-query-form-row">
              <a-col :span="6">
                <a-form-item label="部门" name="deptId">
                  <DepartmentTreeSelect v-if="data.form.edit" :init="false" v-model:value="data.form.deptId"
                    @update:value="change" />
                  <span v-else>{{ data.form.deptName }}</span>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="制单">
                  <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
                </a-form-item>
                <a-form-item label="修改">
                  <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
                </a-form-item>
                <a-form-item label="备注">
                  <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
                  <span v-else>{{ data.form.remark }}</span>
                </a-form-item>
              </a-col>
              <a-col :span="8"></a-col>
            </a-row>
          </a-form>


          <a-row>
            <a-button-group></a-button-group>
            <a-table rowKey="lineNum" style="width: 100%" :dataSource="data.form.lista" :columns="columnsa"
              :scroll="{ y: 700, x: 600 }" :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['20', '30', '40', '50'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }" :default-expand-all-rows="true">
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'qty'">
                  <span>{{ excute(text) }}</span>
                </template>

                <template v-if="column.dataIndex === 'action'">

                  <a-button-group v-if="!data.form.id && data.form.edit">

                    <a-button size="small" @click="handleBatchId(record)" type="link">
                      <FormOutlined />
                    </a-button>

                    <a-button size="small" @click="lineaDel(record)" danger type="link">  
                      <DeleteOutlined />
                    </a-button>

                  </a-button-group>

                </template>
              </template>

              <template #expandedRowRender="{ record }">
                <a-app>
                  <a-table style="width: 100%" :scroll="{ y: 600 }" :dataSource="record.lista" :columns="columnsaa"
                    rowKey="lineNum" :pagination="false">
                    <template #bodyCell="{ text, record, column, index }">
                      <template v-if="column.dataIndex === 'qty'">
                        <span>{{ excute(text) }}</span>
                      </template>
                      <template v-if="column.dataIndex === 'reqQty'">
                        <span>{{ excute(text) }}</span>
                      </template>
                      <template v-if="column.dataIndex === 'invQty'">
                        <span>{{ excute(text) }}</span>
                      </template>
                      <template v-if="column.dataIndex === 'source'">
                        <span>{{ text ? '自制' : '外购' }}</span>
                      </template>
                    </template>
                  </a-table>
                </a-app>
              </template>
            </a-table>







            <a-row style="margin-top: 20px">
              <a-col :span="24">
                <a-button-group v-if="data.form.edit">
                  <a-button @click="save()">保存</a-button>
                  <a-button @click="refresh"> 取消</a-button>
                </a-button-group>
              </a-col>
            </a-row>
          </a-row>
        </a-tab-pane>
        <a-tab-pane key="2" tab="凭证">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-card title="采购暂收送检单">
                <a-table style="width: 100%" :dataSource="data.form.listb" :columns="columnsb" rowKey="lineNum"
                  :scroll="{ y: 650, x: 600 }" :pagination="false">
                  <template #bodyCell="{ text, record, column }">
                    <template v-if="column.dataIndex === 'id'">
                      <a-button type="link" @click="showForm(record, 'suborda')">{{ text }}</a-button>
                    </template>
                  </template>
                </a-table>
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card title="目标凭证">
                <a-table style="width: 100%" :dataSource="data.form.listc" :columns="columnsc" rowKey="lineNum"
                  :scroll="{ y: 650, x: 600 }" :pagination="false">
                  <template #bodyCell="{ text, record, column }">
                    <template v-if="column.dataIndex === 'id'">
                      <a-button type="link" @click="showForm(record, '')">{{ text }}</a-button>
                    </template>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </a-spin>
  <!--  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>-->
  <InvordSelect ref="invordSelect" @onOk="onOk"></InvordSelect>
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { message, Modal, Form } from 'ant-design-vue';
import { smartSentry } from '/src/lib/smart-sentry';
import { approvordApi } from '/src/api/business/erp/approvord-api';
import { useRouter, useRoute } from 'vue-router';
import DepartmentTreeSelect from '/src/components/system/department-tree-select/index.vue';
import Approvord from '/src/components/business/erp/approved.vue';
import { goodsApi } from '/src/api/business/goods/goods-api.js';
import { mrqordApi, mrqordaApi } from '/@/api/business/erp/mrqord-api.js';
import { saordApi } from '/src/api/business/erp/saord-api.js';
import { subordApi } from '/src/api/business/erp/subord-api.js';
import StoSelect from '/src/components/business/erp/sto-select/index.vue';
import { excute } from '/@/utils/numformat-util.js';
import { mrnordaApi, mrnordApi } from '/@/api/business/erp/mrnord-api.js';
import InvordSelect from '/@/components/business/erp/invord-select/index.vue';

const route = useRoute();
const router = useRouter();
const data = reactive({
  form: {
    id: null,
    objId: '',
    absId: '',
    approved: false,
    docStatus: 'O',
    vendId: null,
    vendName: null,
    deptId: null,
    deptName: null,
    edit: false,
    lista: [],
    listb: [],
    listc: [],
  },
  radioGroup: null,
  rules: {
    deptId: [{ required: true, message: '请选择部门' }],
    macName: [{ required: true, message: '请输入设备名称' }],
    macAddress: [{ required: true, message: '请输入设备地址' }],
  },
  model: {
    absId: '',
  },
  doc: {
    tm: 'mrqord',
    tda: 'mrqorda',
  },
  editableData: {
    nowDate: null,
  },
  visible: {
    approvord: false,
  },
  approvedData: {
    baseEntry: null,
    tabName: null,
  },
  itemList: [],
  chooseLinea: null,
  activeKey: '1',
});
const columnsa = ref([
  {
    title: '行号',
    dataIndex: 'lineNum',
    align: 'center',
    width: 80,
  },
  {
    title: '行状态',
    dataIndex: 'lineStatus',
    width: 80,
    align: 'center',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 250,
    align: 'left',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'left',
  },
  {
    title: '规格',
    dataIndex: 'specs',
    width: 400,
    align: 'left',
    ellipsis: true,
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 250,
    align: 'right',
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 120,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 200,
    align: 'center',
  },
]);

const columnsaa = ref([
  {
    title: '行号',
    dataIndex: 'lineNum',
    align: 'center',
    width: 80,
  },
  {
    title: '行状态',
    dataIndex: 'lineStatus',
    align: 'center',
    width: 80,
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 250,
    align: 'left',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'left',
  },

  {
    title: '数量',
    dataIndex: 'qty',
    width: 100,
    align: 'right',
  },

  {
    title: '仓库',
    dataIndex: 'stoName',
    width: 120,
    align: 'center',
  },
  {
    title: '批次',
    dataIndex: 'batchId',
    width: 120,
    align: 'center',
  },
]);
const columnsb = ref([
  {
    title: '基础编码',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '基础行号',
    dataIndex: 'lineNum',
    width: 250,
    align: 'right',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 300,
    align: 'right',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 120,
    align: 'right',
  },
]);

const columnsc = ref([
  {
    title: '目标编码',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '目标行号',
    dataIndex: 'lineNum',
    width: 250,
    align: 'right',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 300,
    align: 'right',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 120,
    align: 'right',
  },
]);
const tableLoading = ref(false);
const formRef = ref(null);

// 初始化
function init() {
  if (route.query.type === 'info') {
    data.form.id = route.query.id;
    queryData();
  } else if (route.query.type === 'tager') {
    tableLoading.value = true;

    mrqordApi
      .infoUnexecute(route.query.id)
      .then((res) => {
        data.form = res.data;
        data.form.edit = true;
        data.form.lista.forEach((item) => {
          item.edit = true;
        });
      })
      .finally(() => {
        tableLoading.value = false;
        data.form.edit = true;
      });
  } else {
    data.form.edit = true;
  }
}

// 更多操作
function more({ key }) {
  // 审核处理函数
  if (key === 'a') {
    data.form.docStatus = 'C';
    tableLoading.value = true;
    mrqordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'b') {
    data.form.docStatus = 'O';
    tableLoading.value = true;
    mrqordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'c') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'A',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'd') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'B',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'e') {
  }
}

function save() {
  formRef.value
    .validate()
    .then(() => {
      tableLoading.value = true;
      if (data.form.id) {
        mrqordApi
          .update(data.form)
          .then((res) => {
            queryData(data.form.id);
            message.success('修改成功！');
          })
          .finally(() => {
            tableLoading.value = false;
          });
      } else {
        mrqordApi
          .add(data.form)
          .then((res) => {
            data.form.id = res.data;
            message.success('保存成功！');
            router.push({ path: data.doc.tda, query: { type: 'info', id: res.data } });
            queryData(res.data);
          })
          .finally(() => {
            tableLoading.value = false;
          });
      }
    })
    .catch((err) => {
      message.error('页面校验失败！');
    });
}

function edit() {
  data.form.edit = true;

  data.form.lista.forEach((item) => {
    item.edit = true;
  });
}

function del() {
  Modal.confirm({
    content: `确认删除（${data.form.id}）`,
    onOk() {
      mrqordApi.delete(data.form.id).then((res) => {
        message.success('删除成功！');
        router.push({ path: data.doc.tm });
      });
    },
    cancelText: '取消',
    onCancel() {
      Modal.destroyAll();
    },
  });
}

async function queryData() {
  tableLoading.value = true;
  formRef.value.resetFields();
  try {
    let queryResult = await mrqordApi.info(data.form.id);
    data.form = queryResult.data;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

function refresh() {
  queryData();
}

function back() {
  router.push({ path: data.doc.tm });
}

function change(item, key) {
  data.form.deptName = key;
}

// 审核------------------------------------------------------------------------------------------------
function approved() {
  data.approvedData.baseEntry = data.form.id;
  data.approvedData.tabName = data.form.objName;
  data.visible.approvord = true;
}

function onclose() {
  data.visible.approvord = false;
  queryData();
}

// 行----------------------------------------------a-------------------------------------------------------

function onOk(item) {
  item.forEach((it) => {
    data.chooseLinea.lista.push({
      id: data.form.id,
      lineNum: data.chooseLinea.lista.length + 1,
      baseId: data.chooseLinea.id,
      baseLineNum: data.chooseLinea.lineNum,
      lineStatus: 'O',
      itemId: data.chooseLinea.itemId,
      itemName: data.chooseLinea.itemName,
      qty: it.selQty,
      batchId: it.batchId,

      stoId: it.stoId,
      stoName: it.stoName,
    });
  });
}

const invordSelect = ref();

function handleBatchId(item) {
  data.chooseLinea = item;
  invordSelect.value.showModal(item);
}

function StoChange() { }

function qtyChange(item) {
  item.priceLine = (item.qty * item.price).toFixed(4);
  item.taxPriceLine = (item.taxPrice * item.tax * item.qty).toFixed(4);
}

function queryItemList() {
  goodsApi
    .queryGoodsList({
      pageNum: 1,
      pageSize: 10,
    })
    .then((res) => {
      data.itemList = res.data.list;
    })
    .catch((err) => { })
    .finally(() => { });
}

function lineaEdit(key) {
  key.edit = true;
}

function lineaAdd() {
  data.form.lista.push({
    id: data.form.id,
    lineNum: data.form.lista.length + 1,
    lineStatus: 'O',
    qty: 1,
    edit: true,
  });
}

function lineaDel(item) {
  item.del = true;
}

// --------------------------------凭证

function showForm(data, it) {
  router.push({ path: it, query: { type: 'info', id: data.id } });
}

onMounted(() => {
  init();
  queryItemList();
});
</script>
